/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.InqueryDAOInterface;
import com.wii.elpro.dao.hb.InqueryDAOImpl;
import com.wii.elpro.entity.Inquery;
import com.wii.elpro.entity.InqueryItem;
import com.wii.elpro.entity.User;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class InquirySaveItemAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        ActionForward af = null;
        InqueryDAOInterface dao = new InqueryDAOImpl();       
        ActionMessages messages = new ActionMessages();
        String id;
        if(sess.getAttribute("idInquiry")!=null) {
            id = (String) sess.getAttribute("idInquiry");
        } else {
            id = 0+"";
        }
        try {
            if(sess.getAttribute("idInquiry")!=null && sess.getAttribute("listItem")!=null) {
                List<InqueryItem> items = (List<InqueryItem>) sess.getAttribute("listItem");
                Inquery inquiry = dao.getInquery(Long.parseLong((String) sess.getAttribute("idInquiry")));
                inquiry.getItems().addAll(items);

                dao.update(inquiry);
                sess.removeAttribute("listItem");
                messages.add("customMessage", new ActionMessage("customMessage", "Your data is successfully saved."));
                saveMessages(sess, messages);
            } else {
                messages.add("message", new ActionMessage("customMessage", "There is no item(s) requested to save."));
                saveMessages(sess, messages);
            }
            af = new ActionForward(mapping.findForward("success").getPath()+"?id="+id, true);
        } catch (Exception ex ) {
            messages.add("message", new ActionMessage("customMessage", "Application is fail to save your data. Please contact my developer."));
            saveMessages(sess, messages);
            ex.printStackTrace();
            af = new ActionForward(mapping.findForward("fail").getPath()+"?id="+id, true);
        }
        return af;
    }
}
